var GLOBAL_PARAMS = {//全局缓存变量
    DICT_CACHE: {},
    AUTHORITY_CACHE: []
};

var monitorMenu = [];

//界面初始化模块
define('pageInit', function () {
	
	//TODO
	var host = window.location.host;
	
//	if(host.indexOf($("#scOuterIp").val())>=0 || host.indexOf($("#scInnerIp").val())>=0){
//	}	
	/*if(host.indexOf($("#scOuterIp").val())>=0){
		$("#ewm").hide();
		$("#sc_ewm2").hide();
		$("#sc_ewm1").show();
	}else if(host.indexOf($("#scInnerIp").val())>=0){
		$("#ewm").hide();
		$("#sc_ewm1").hide();
		$("#sc_ewm2").show();
	}*/
	
	$.ajaxExt({
    	url : "/logon/commonUrlInfo.htm"
    }).done(function(data){
        if(host.indexOf(data.innerIp)>=0){
        	$("#ewmPic").attr("src", data.innerMainEwm);
        }else{
        	$("#ewmPic").attr("src", data.outerMainEwm);
        }
    });
	
	$.ajaxExt({
		url :"/sysCorpInfo/loadCorpLogo.htm"
	}).done(function(data){
//		console.info(data.logoPath);
		if(typeof(data.logoPath)=="undefined"){
			$(".site-logo").attr("src",'./content/images/logo_06.png');
		}else{
			$(".site-logo").attr("src",$.getProjectName() + "/baseBlackArchivesInfo/readImage.htm?uploadPath=" + data.logoPath);
		}
	});
		
//	}else{
//		
//	}

    //创建菜单栏
    function createMenuBar(data) {

        var $con = $('<nav class="site-main-nav"></nav>');
        var $menu, $second, $fourth;//1、2、4级菜单
        var $dropDown, $secondCon, $thirdCon, $fourthCon;//下拉、二级菜、三级、四级菜单父节点
        var $rightCon;//下拉菜单右侧区域

        function pushMenuJson(data) {
            var obj = {};
            obj[data.id] = {
                url: data.url,
                name: data.name,
                treeConfig: data.submenuSet ? $.strToJson(data.submenuSet) : '',
                fifth: data.child
            };
            baseData.menu.push(obj);
        }

        var firstOpenMenu;
        $.each(data, function (i, d) {
            $menu = $(('<div class="item {0}">' +
            '       <span class="icon-flag"></span>' +
            '       <p class="text">{1}</p>' +
            '      </div>').format(d.css, d.name)).appendTo($con);

            if (d.child) {
                $dropDown = $('<div class="menu-box menu-box2 clearfix pb20"></div>').appendTo($menu);
                $secondCon = $('<div class="menu-tab"></div>').appendTo($dropDown);
                $thirdCon = $('<div class="menu-tab-ct"></div>').appendTo($dropDown);
                $.each(d.child, function (i2, d2) {
                    $second = $('<div class="tab-item">' + d2.name + '</div>').appendTo($secondCon);
                    $rightCon = $('<div class="ct-item"></div>').appendTo($thirdCon);
                    if (i2 === 0) {
                        $second.addClass('active');
                        $rightCon.addClass('active');
                    }
                    $.each(d2.child, function (i3, d3) {
                        $fourthCon = $('<div class="list"><h3>' + d3.name + '</h3><ul></ul></div>').appendTo($rightCon).find('>ul');
                        $.each(d3.child, function (i4, d4) {
                            if (d4.monitorFlag && d4.child && d4.child.length) {//用于监控菜单显示在机务首页

                                $.each(d4.child, function (i5, d5) {
                                    if (d5.monitorFlag) {
                                        monitorMenu.push(d4.id);
                                        return false;
                                    }
                                })
                            }
                            $fourth = $('<li><a class="btn-overlay">' + d4.name + '</a></li>').appendTo($fourthCon).find('>a');
                            pushMenuJson(d4);
                            $fourth.data('data-id', d4.id);
                        });
                        if (i3 > 0 && (i3 + 1) % 4 === 0) {
                            var $div = $('<div class="clearfix"></div>').appendTo($rightCon);
                            $('>div.list', $rightCon).appendTo($div);
                        }
                    });
                });
            } else {
                pushMenuJson(d);
                if (!firstOpenMenu) {
                    firstOpenMenu = $menu;
                }
                $menu.data('data-id', d.id).on('click', function () {
                    openTab($(this).data('data-id'));
                });
            }
        });

        $('#topBar').append($con);

        $con.on('click', 'a', function () {
            openTab($(this).data('data-id'));
        });

        $(".tab-item", $con).each(function () {
            $(this).hover(function () {

                    $(this).addActiveClass();
                    $(this).parent().siblings(".menu-tab-ct").find(".ct-item").eq($(this).index()).show().siblings().hide();
                }
            )
        });

        if (firstOpenMenu) {
            firstOpenMenu.trigger('click');
        }
    }

    function loadInitData() {

        //获取菜单
        var req1 = $.ajaxExt({
            url: '/logon/getMenuListByUser.htm',
            success: function (result) {
                createMenuBar(result);
            }
        });
        //加载数据字典
        var req2 = $.ajaxExt({
            url: '/system/cache/codes.htm',
            data: {
                codes: ['SYS_CODE']
            },
            success: function (result) {
                GLOBAL_PARAMS.DICT_CACHE = result || {};
            }
        });
        //TODO 加载权限缓存
        var req3 = $.ajaxExt({
           url: '/sysAuthorityFunc/getCheckedFuncCache.htm',
           success: function (result) {
               if(result){
                   var cache = [];
                    $.each(result, function(index, item){
                        cache.push(item.id);
                    });
                   GLOBAL_PARAMS.AUTHORITY_CACHE = cache || [];
               }
           }
        });

        var req4 = $.ajaxExt({
            url: '/logon/getCurrentUser.htm',
            success: function (result) {
                $('#userNameLabel').text(result.name);
                window.getUserInfo = function () {
                    return result;
                };
            }
        });

        $.when(req1, req2, req3, req4).always(function () {
            $('#m-mask').remove();
        });
    }

    var baseData = {
        menu: [],
        loadInitData: loadInitData
    };

    $("#changePsw").click(function () {
        $.openTab('c474db1055de485c8509f7163dbe670b');
    });

    //通知栏
    (function () {

        var $noticeList = $('#noticeList');

        function noticeAnimate() {

            function move() {
                $noticeList.animate(
                    {"marginTop": -20 + "px"},
                    600,
                    function () {
                        $noticeList.css({marginTop: 0}).find("p:first").appendTo($noticeList); //appendTo能直接移动元素
                    }
                );
            }


            function auto() {
                return setInterval(function () {
                    move();
                }, 2600);
            }


            
            
            var t = auto();

            $noticeList.hover(function () {
                clearInterval(t);
            }, function () {
                t = auto();
            });
        }

        //加载系统公告
        $.ajaxExt({
            url: "/logon/getNoticeList.htm"
        }).done(function (data) {
            var html = "";
            if (data && data.length > 0) {
                $.each(data, function (index, obj) {
                    html += '<p><a data-val="{0}">{1}</a></p>'.format(obj.announId, obj.announTitle);
                });
                $('#noticeList').html(html);
                //data.length > 1 && 
                noticeAnimate();
            }
        });

        $noticeList.on('click', 'a', function () {
            $.openTab('b4b7f77cce3d49368503836be2e4ae2e', 'toContent', [$(this).attr('data-val')]);
        });
    })();
    

    $('#warn-list').on('click', 'li', function () {
        var memuId = $(this).attr('data-menuid'),//目标菜单的ID
            methodName = $(this).attr('data-method');//目标界面所要执行的方法
        $.openTab(memuId, methodName);
    });

    //注销
    $('#logout').on('click', function () {
        $.messager.confirm('注销', '确定要注销当前用户吗？', function (r) {
            if (r) {
                window.location = $.getProjectName() + '/logon/commonQuit.htm';
            }
        })
    });


    //框架高度初始化
    (function () {

        var $iframeContainer = $('#iframeContainer');

        function heightInit() {
            var height = $(window).height();
            $iframeContainer.height(height - 155);
            $('#carLeftTreeUl').parent().height(height - 237);
        }

        function menuStyle() {
            var width = $(window).width();
            var $nav = $('nav.site-sub-nav2', $iframeContainer);
            var subCss = 'site-sub-nav2-2';
            if (width > 1600) {
                $nav.each(function () {
                    if ($(this).hasClass(subCss)) {
                        $(this).removeClass(subCss);
                        $('i.arrow-tip,span.text', this).attr('style', '');
                        $('>ul>li', this).unbind("mouseenter").unbind("mouseleave");
                    }
                });
            } else {
                $nav.each(function () {
                    if (!$(this).hasClass(subCss)) {
                        $(this).addClass(subCss);
                        $('>ul>li', this).hover(function () {
                            if ($(this).closest('nav').hasClass(subCss)) {
                                $('i,span.text', this).show();
                            }
                        }, function () {
                            if ($(this).closest('nav').hasClass(subCss)) {
                                $('i,span.text', this).hide();
                            }
                        });
                    }
                });
            }
        }

        $(window).on('resize', function () {
            heightInit();
            menuStyle();
        }).trigger('resize');
    }());

    return baseData;
});

//报警及在线离线推送Socket模块
define('socketInit', ['swfobject'], function () {
    var $noticeBox = $('#notice-box');

    //声音开关
    var $voiceSwitch = $('.icon-info', $noticeBox).on('click', function () {
        if (this.className.indexOf('icon-info-close') == -1) {
            sound.pause();
        }
        $voiceSwitch.toggleClass('icon-info-close');
    });

    var url = $.getProjectName() + "/content/images/msg.wav";

    var sound;
    var ua = navigator.userAgent.toLowerCase();
    if (/msie/.test(ua) || /trident/.test(ua)) {
        //本来这里用的是<bgsound src="system.wav"/>,结果IE8不播放声音,于是换成了embed
        sound = $("<embed id='audio' autostart='false' src='" + url + "' style='height:0;'/>").appendTo($voiceSwitch)[0];
    } else {
        //IE9+,Firefox,Chrome均支持<audio/>
        sound = $('<audio id="audio"><source src="' + url + '" ' + 'type="audio/wav"/></audio>').appendTo($voiceSwitch)[0];
    }

    var searchCountReq;
    $noticeBox.on('click', function (e) {
        var $target = $(e.target || e.srcElement);
        if ($target.closest('.pop-layer-wrap').length || $target.hasClass('.pop-layer-wrap')) {
            return;
        }

        var _$t = $(this);
        if (_$t.hasClass('notice-box-active')) {
            if (!searchCountReq) {
                getCount();
            }
            _$t.removeClass('notice-box-active');
        }
        $('.pop-layer-wrap', this).show();
    }).hover($.noop, function () {
        $('.pop-layer-wrap', this).hide();
    });

    //获取异常总数
    function getCount() {
        searchCountReq = $.ajaxExt({
            url: "/warn/getWarnLightInfo.htm"
        }).done(function (data) {
            searchCountReq = null;
            var $overSpeedWarn = $("#overSpeedWarn"),
                $carFaultWarn = $("#carFaultWarn"),
                $drvExceptionWarn = $("#drvExceptionWarn");
            var total = 0;
            if ($overSpeedWarn.length && data.overSpeed != null) {
                $overSpeedWarn.empty().html(data.overSpeed);
                total = total + parseInt(data.overSpeed);
            }
            if ($carFaultWarn.length && data.fault != null) {
                $carFaultWarn.empty().html(data.fault);
                total = total + parseInt(data.fault);
            }
            if ($drvExceptionWarn.length && data.unsafeAction != null) {
                $drvExceptionWarn.empty().html(data.unsafeAction);
                total = total + parseInt(data.unsafeAction);
            }
            $("#exceptionTotal").html(total);
        });
    }

    //设置左侧树车辆状态（在线、不在线）
    function setCarStatus(msg) {
        msg = msg.replace(/[\r\n]/g, "");
        msg = msg.replace(new RegExp("\}\{", "g"), "},{");
        var msgData = eval("[" + msg + "]");
        $.each(msgData, function () {
            commonFun.setCarStatus(this.carId, this.status);
        });
    }

    function initAs() {
        var localSocketServer;
        var vm = swfobject.getObjectById("warningSwf");
        $('#warningSwf').css('position', 'fixed');
        
        //TODO
        //判断是否为思创ip
        var host = window.location.host;
        if(host.indexOf($("#innerIp").val())>=0){
        	if (!$("#innerLocalSocketServer").length) {
        		return;
        	}
        	localSocketServer = $("#innerLocalSocketServer").val();
        	vm.callFromJsConn(localSocketServer);
        }else{
        	if (!$("#localSocketServer").length) {
        		return;
        	}
        	localSocketServer = $("#localSocketServer").val();
        	vm.callFromJsConn(localSocketServer);
        }

    }

    //发送请求
    function sendToAs() {
        var vm = swfobject.getObjectById("warningSwf");
        vm.callFromJsSend("{type:0,userId:'" + $("#userId").val() + "'}");
    }

    //接收请求
    window.callfromAs = function (msg) {
        try {
            if (msg == "连接建立!") {
                sendToAs();
            } else if (msg == "连接关闭!") {
                $.messager.alert("警告", "与设备连接关闭!", "warning");
            } else if (msg.indexOf("warn") > -1) {
                $noticeBox.addClass('notice-box-active');
                if (!$voiceSwitch.hasClass('icon-info-close')) {
                    sound.play();
                }
                msg = msg.replace(new RegExp(/(warn)/g), "").replace(/[ ]/g, "").replace(/[\r\n]/g, "");                
                if (msg != "") {
                    setCarStatus(msg);
                }

            } else {
                setCarStatus(msg);
            }
        } catch (e) {
        }
    };

    window.callfromAsCompl = function () {
        initAs();
    };
    swfobject.embedSWF($.getProjectName() + "/component/socketSwf/CommFlexSocket.swf?a=" + Math.random(),
        "warningSwf", "0", "0", "9.0.0", $.getProjectName() + "/component/socketSwf/expressInstall.swf");
    
    //TODO
    var url;
    var host = window.location.host;
    if(host.indexOf($("#innerIp").val())>=0){
    	url = 'ws://'+$("#innerLocalSocketServer2").val();
    }else{
    	url = 'ws://'+$("#localSocketServer2").val();
    }
    
	
	var ws;
	if ('WebSocket' in window) {
		ws = new WebSocket(url);
	} else if ('MozWebSocket' in window) {
		ws = new MozWebSocket(url);
	}
	
	ws.onopen = function() {
			ws.send("{type:0,userId:'" + $("#userId").val() + "'}");
		};
	ws.onmessage = function(event) {
			
			try {
				var msg=event.data;
            if (msg == "连接建立!") {
                
            } else if (msg == "连接关闭!") {
                $.messager.alert("警告", "与设备连接关闭!", "warning");
            } else if (msg.indexOf("warn") > -1) {
                
                msg = msg.replace(new RegExp(/(warn)/g), "").replace(/[ ]/g, "").replace(/[\r\n]/g, "");
                if (msg != "") {
                    setCarStatus(msg);
                }

            } else {
                setCarStatus(msg);
            }
        } catch (e) {
        }
		};
	ws.onerror = function(event) {
		};
	ws.onclose = function() {
				
			};	
});

//tab模块
define('canTab', ['pageInit', 'leftOrg', 'zTreeCheckbox'], function (baseData) {

    var leftTreeInit = false;//左侧树是否初始化
//主界面中的tab组件
    $.canui('canTab', {
        _create: function () {
            var html = '<a class="pull-left"></a>' +
                '           <div class="tab-inner" style="height: 34px;">' +
                '               <div style="height: 100%;overflow: hidden;width: 0;padding-left: 20px;">' +
                '               </div>' +
                '           </div>' +
                '       <a class="pull-right"></a>';
            var _$top = this.element.append(html);
            this.titleContainer = $('.tab-inner>div', _$top);
            this.iframeContainer = $('#iframeContainer');

            this.titleContainer.parent().width($(document).width() - 90);

            var _t = this;
            $('>.pull-left', _$top).on('click', function () {
                _t._tabTitleScroll(false);
            });

            $('>.pull-right', _$top).on('click', function () {
                _t._tabTitleScroll(true);
            });

            this.titleContainer.sortable({
                axis: "x",
                stop: function (event, ui) {
                    ui.item.attr('style', '');//拖拽完成后会给目标元素自动添加一些样式，导致和现有的会有一些冲突
                }
            }).disableSelection();

            this.titleContainer.on('click.show', 'span', function (e, fn, fifthId) {
                if ((e.target || e.srcElement).className === "close-btn") {//点击tabTitle上面的关闭按钮也会触发此事件
                    return;
                }
                _t._showTab($(this), fn, fifthId);

                var width = _t.titleContainer.width() + 20;
                var parentWidth = _t.titleContainer.parent().width();
                if (parentWidth < width) {
                    var marginLeft = $.getStyleNum(_t.titleContainer, 'margin-left');
                    var beforeWidth = 0;
                    $.each($(this).nextAll(), function (index, item) {
                        beforeWidth += $(item).outerWidth();
                        if (index > 0) {
                            beforeWidth -= 20;
                        }
                    });
                    if (marginLeft < -beforeWidth + 20) {//tabTitle左侧被覆盖
                        _t.titleContainer.css('margin-left', beforeWidth == 0 ? 0 : -beforeWidth + 20);
                    } else {
                        var subVal = beforeWidth + $(this).outerWidth() + marginLeft - parentWidth - 20;
                        if (subVal > 0) {//tabTitle右侧被覆盖
                            _t.titleContainer.css('margin-left', marginLeft - subVal);
                        }
                    }

                } else {
                    var div = _t.titleContainer[0];
                    if (div.style.marginLeft) {
                        div.style.marginLeft = "0";
                    }
                }
            }).on('click.close', '.close-btn', function () {
                _t.closeTab($(this).parent());
            });
        },
        _getIframeDiv: function (menuId) {//根据菜单ID获取对应的iframeDiv
            var _t = this;
            var $iframe = null;
            var isFifth;
            $.each($('>div', _t.iframeContainer), function (index, item) {
                if ($(item).data('menuId') == menuId) {
                    $iframe = $(item);
                    return false;
                } else if ($(item).find('>.site-sub-nav').length) {
                    $.each($(item).find('li'), function (i, d) {
                        if ($(d).data('menuId') == menuId) {
                            $iframe = $(d);
                            isFifth = true;
                            return false;
                        }
                    });
                    if (isFifth) {
                        return false;
                    }
                }
            });
            return $iframe;
        },
        _showTab: function ($title, fn, fifthId) {
            var _t = this;
            var _$t = $title;
            var menuId = _$t.data('menuId');
            var _$iframe = _t._getIframeDiv(menuId);


            function fnExec() {

                if (fifthId) {
                    $.each(_$iframe.find('li'), function (i, d) {
                        if ($(d).data('menuId') === fifthId) {
                            $(d).trigger('click');
                            return false;
                        }
                    });
                }

                if ($.isFunction(fn)) {
                    var $iframe = _$iframe.find('iframe');
                    var contentWindow = $iframe[0].contentWindow;

                    //iframe的src有可能改变了，但是此时的document的状态仍然是ready状态
                    if (contentWindow && contentWindow.$ && contentWindow.$.isReady && contentWindow.document.location.pathname.indexOf($iframe.attr('src').replace('.', '')) != -1) {
                        fn.call(contentWindow);
                    } else {
                        $iframe.one('load.first', function () {
                            if (fn.funcName) {
                                var _win = this.contentWindow;
                                $.deferExecuteFn.call(_win, fn);
                            }
                        });
                    }
                }
            }

            if (_$t.hasClass('active')) {
                fnExec();
                return;
            }
            _$t.addActiveClass();
            if (!_$iframe) {
                return;
            }
            _t.iframeContainer.find('>div:visible').hide();
            //是否显示左侧树
            var json = this._toggleLeftTree(menuId);
            _$iframe.show();
            if (json[0].fifth) {//菜单下面有五级菜单时
                _t._currentTabTreeConfig = $('nav li.active', _$iframe).data('treeConfig');
                _t._leftTreeOper();
            } else if (json[0].treeConfig) {
                _t._currentTabTreeConfig = json[0].treeConfig;
                _t._leftTreeOper();
            } else {
                _t._currentTabTreeConfig = '';
            }


            fnExec();
        },
        /**
         * 返回菜单数据信息
         * @param menuId
         * @returns {Array} 如果是5级菜单，返回的是长度为2的数组，第一个值为父菜单信息，第二个为子菜单信息；
         * 不是5级菜单的就直接返回菜单menuId的数据信息
         * @private
         */
        _getMenuJson: function (menuId) {
            var obj = [];
            var pId, ret = false;
            $.each(baseData.menu, function (i, data) {
                if (data[menuId]) {
                    obj[0] = data[menuId];
                    return false;
                } else {
                    for (var prop in data) {
                        pId = prop;
                    }
                    if (data[pId].fifth) {
                        $.each(data[pId].fifth, function (i2, d2) {
                            if (d2.id == menuId) {
                                obj[0] = data;
                                obj[1] = d2;
                                ret = true;
                                return false;
                            }
                        });
                        if (ret) {
                            return false;
                        }
                    }
                }
            });
            return obj;
        },
        _tabTitleScroll: function (isRight) {//左右滚动tabTitle
            var titleConParent = this.titleContainer.parent();
            var parentWidth = titleConParent.width();
            if (parentWidth >= this.titleContainer.width()) {
                return;
            }

            var marginLeft = $.getStyleNum(this.titleContainer, 'margin-left'),
                stepNum = 30;//每次滚动的大小
            var val = isRight ? -stepNum : stepNum;
            if (!isRight && val + marginLeft > 0) {
                val = -marginLeft;
            } else if (isRight && Math.abs(val + marginLeft) + parentWidth > this.titleContainer.width() + 20) {
                val = -(this.titleContainer.width() + 20 - parentWidth + marginLeft);
            }

            this.titleContainer.css({
                'margin-left': (marginLeft + val) + 'px'
            });

        },
        _openTab: function (menuId, callback) {//打开新的tab页
            var _t = this;
            var hasOpen = false;//tab是否已经打开
            var fifthId;

            var json = _t._getMenuJson(menuId),
                len = json.length;
            if (!len) {
                return;
            }
            if (len == 1) {
                if (json[0].fifth) {
                    fifthId = true;
                }
            } else {
                fifthId = menuId;
                for (var prop in json[0]) {
                    menuId = prop;
                }
            }

            $.each($('>span', this.titleContainer), function (index, item) {
                if ($(item).data('menuId') == menuId) {
                    hasOpen = true;
                    $(item).trigger('click', [callback, typeof fifthId === 'string' ? fifthId : undefined]);
//                if (typeof fifthId === 'string') {
//                    $.each($fifthCon.find('li'), function (i, d) {
//                        if ($(d).data('menuId') === fifthId) {
//                            $(d).trigger('click');
//                            return false;
//                        }
//                    });
//                }
                    return false;
                }
            });
            if (!hasOpen) {
                this._addTab(menuId, fifthId, callback);
            }
        },
        _currentTabTreeConfig: null,//保存当前tab页的左侧树配置信息
        /**
         * 获取当前tab页的左侧树配置信息
         * @returns {json|null}
         */
        getCurrentTabTreeConfig: function () {
            return this._currentTabTreeConfig;
        },
        _addTab: function (menuId, fifthId, callback) {//新增一个tab
            //是否显示左侧树
            var _t = this;
            var json = _t._toggleLeftTree(menuId);

            var isFifth = !!fifthId;//菜单是否包含5级菜单，或者为5级菜单

            var menuName = json[0].name;
            var src = isFifth ? '' : json[0].url;

            var $activeTab = this.titleContainer.find('>span.active');
            var $tabTitle;
            if ($activeTab.length) {
                $tabTitle = $('<span>' + menuName + '<i class="close-btn"></i></span>').insertBefore($activeTab);
            } else {
                $tabTitle = $('<span>' + menuName + '<i class="close-btn"></i></span>').appendTo(this.titleContainer);
            }
            $tabTitle.data('menuId', menuId);

            //if (menuName.length > 8) {
            //    $tabTitle.addWidth(12 * (menuName.length - 8));
            //}

            var width = $tabTitle.outerWidth() - 20;
            _t.titleContainer.addWidth(width);

            var subVal = this.titleContainer.width() + 20 - this.titleContainer.parent().width();
            if (subVal > 0) {
                var marginLeft = $.getStyleNum(this.titleContainer, 'margin-left');
                if (marginLeft == 0) {
                    this.titleContainer.css('margin-left', -subVal + 'px');
                } else {
                    this.titleContainer.css('margin-left', marginLeft - width + 'px');
                }
            }

            var $div = $('<div class="wh100"></div>').appendTo(this.iframeContainer);

            function initLeftTree(fn) {
                if (!leftTreeInit) {

                    leftTreeInit = true;
                    $('#leftTreeArea').leftOrg({
                        callback: fn
                    });
                } else {
                    fn();
                }
            }

            if (isFifth) {
                var isMin1600 = $(window).width() < 1600;
                var $fifthCon = $('<nav class="site-sub-nav2 {0}"><ul></ul></nav>'.format(isMin1600 ? "site-sub-nav2-2" : '')).appendTo($div);

                var $fifthMenu;
                $.each(json[0].fifth, function (i, data) {
                    $fifthMenu = $(('<li><a class="{0}">' +
                    '<span class="icon"></span>' +
                    '<i class="arrow-tip"></i>' +
                    '<span class="text">{1}</span>' +
                    '</a></li>').format(data.css, data.name)).appendTo($('>ul', $fifthCon));
                    $fifthMenu.data('menuId', data.id).data('src', data.url).data('treeConfig', $.strToJson(data.submenuSet || ''));
                });

                if (isMin1600) {
                    $('li', $fifthCon).hover(function () {
                        if ($(this).closest('nav').hasClass('site-sub-nav2-2')) {
                            $('i,span.text', this).show();
                        }
                    }, function () {
                        if ($(this).closest('nav').hasClass('site-sub-nav2-2')) {
                            $('i,span.text', this).hide();
                        }
                    });
                }

                $fifthCon.on('click', 'li', function () {
                    var that = this;
                    if (!$(that).hasClass('active')) {
                        $(that).addActiveClass();
                        _t._destroyDialog($(that).closest('div.wh100'));
                        var treeConfig = $(that).data('treeConfig');
                        _t._currentTabTreeConfig = treeConfig;

                        if(!treeConfig){
                            _t._toggleLeftTree(false);
                            $(that).closest('nav').next().find('>iframe').attr('src', $(that).data('src'));
                        }else{
                            initLeftTree(function () {
                                _t._leftTreeOper();
                                $(that).closest('nav').next().find('>iframe').attr('src', $(that).data('src'));
                            });
                        }
                    }
                });
            } else {
                _t._currentTabTreeConfig = json[0].treeConfig;
            }

            var $iframe = $('<iframe frameborder="0" width="100%" height="100%;" style="position: absolute;"></iframe>').appendTo($div);
            $div.data('menuId', menuId);
            $iframe.wrap('<div style="position: relative;overflow: hidden;height: 100%;"></div>');

            function loadIframe() {
                if (!isFifth) {
                    $iframe.attr('src', src);
                    $tabTitle.trigger('click', callback);
                } else {
                    $tabTitle.trigger('click', callback);
                    if (typeof fifthId === 'string') {
                        $.each($fifthCon.find('li'), function (i, d) {
                            if ($(d).data('menuId') === fifthId) {
                                $(d).trigger('click');
                                return false;
                            }
                        });
                    } else {
                        $fifthCon.find('li:eq(0)').trigger('click');
                    }
                }
            }

            if (!leftTreeInit) {

                if (json.length) {
                    var treeConfig = json[0].treeConfig;
                    if (!!treeConfig) {
                        initLeftTree(loadIframe);
                        return;
                    }
                }
            }
            loadIframe();
        },
        /**
         * 根据配置操作左侧树
         * @private
         */
        _leftTreeOper: function () {
            var _t = this;
            _t._toggleLeftTree(!!_t._currentTabTreeConfig);
            _t._execLeftTreeOper();
        },
        _execLeftTreeOper: function () {
            var treeConfig = this._currentTabTreeConfig;
            if (treeConfig && treeConfig.treeType) {
                commonFun.showLeftTree(treeConfig.treeType);
            }
            if (treeConfig && treeConfig.checkEnable !== null) {
                commonFun.changeLeftTreeCheckboxEnable(treeConfig.checkEnable);
            }
        },
        /**
         * 切换左侧树显示隐藏
         * @param menuId
         * @returns {JSON|NULL} 对应的菜单JSON
         * @private
         */
        _toggleLeftTree: function (menuId) {
            var _t = this;
            var _$left = $('#leftTreeArea');
            var status = _$left.is(':visible');

            function toggleLeftTree(show) {
                if (!leftTreeInit) {
                    return;
                }
                if (status !== show) {
                    if (show) {
                        _$left.css('margin-left', 0).find('>.slide-panel').removeClass('slide-panel-active');
                        _$left.show();
                    } else {
                        _$left.hide();
                        _$left.css('margin-left', -250);
                    }
                }
            }


            if (typeof menuId === 'boolean') {
                toggleLeftTree(menuId);
            } else {
                var json = _t._getMenuJson(menuId);

                if (json.length) {
                    var treeConfig = json[0].treeConfig;
                    if (!json[0].fifth) {
                        var show = !!treeConfig;
                        toggleLeftTree(show);
                    }
                }
                return json;
            }
        },
        closeTab: function ($title) {//关闭一个tab
            if ($title.siblings().length == 0) {//只剩下最后一个tab时不关闭
                return;
            }
            var _t = this;

            var menuId = $title.data('menuId');

            var $div = _t._getIframeDiv(menuId);
            if ($div) {
                _t._destroyDialog($div);
                $div.remove();
            }

            var width = $title.outerWidth();
            this.titleContainer.addWidth(-width + 20);
            if ($title.hasClass('active')) {
                var $tabTitle;
                $tabTitle = $title.next();
                if (!$tabTitle.length) {
                    $tabTitle = $title.prev();
                }
                $title.remove();
                $tabTitle.trigger('click');
            } else {
                $title.remove();
            }

            var subVal = _t.titleContainer.width() - _t.titleContainer.parent().width();
            if (subVal > 0) {
                var marginLeft = $.getStyleNum(_t.titleContainer, 'margin-left');
                _t.titleContainer.css('margin-left', marginLeft > -width ? 0 : marginLeft + width + 'px');
            }
        },
        _destroyDialog: function ($div) {
            var $iframe = $('iframe', $div);
            if ($iframe.length) {
                var fn = $iframe[0].contentWindow.commonFun;
                if (fn) {//销毁子界面弹出的窗体
                    fn.destroyDialog();
                }
            }
        }
    });


    return {
        init: function () {
            $('#tabTop').canTab();
            baseData.loadInitData();
        }
    };
});

function openTab(id, callback) {
    $('#tabTop').canTab('_openTab', id, callback);
}

require(['canTab', 'dialog', 'socketInit', 'jquery-ui'], function (canTab) {

    canTab.init();

});
